package com.z.redis.command.impl.string;

import com.sun.corba.se.impl.orbutil.LogKeywords;
import com.z.redis.RedisCore;
import com.z.redis.command.Command;
import com.z.redis.command.CommandType;
import com.z.redis.datatype.BytesWrapper;
import com.z.redis.datatype.RedisData;
import com.z.redis.datatype.RedisString;
import com.z.redis.resp.BulkString;
import com.z.redis.resp.Resp;
import com.z.redis.resp.RespArray;
import io.netty.channel.ChannelHandlerContext;
import sun.awt.image.ImageWatched;

import java.util.LinkedList;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 *  MGET KEY1 KEY2 .. KEYN
 *  批量获取多个值
 */
public class Mget implements Command {
    private List<BytesWrapper> keys;

    @Override
    public CommandType type(){
        return CommandType.mset;
    }

    @Override
    public void setContent(Resp[] array){
        keys = Stream.of(array)
                .skip(1)
                .map(resp -> ((BulkString) resp).getContent())
                .collect(Collectors.toList());
    }

    @Override
    public void handle(ChannelHandlerContext ctx, RedisCore redisCore){
        LinkedList<BytesWrapper> results = new LinkedList<>();
        keys.forEach(key -> {
            RedisData redisData = redisCore.get(key);
            if(redisData != null){
                if(redisData instanceof RedisString){
                    results.add(((RedisString) redisData).getValue());
                }else{
                    throw new UnsupportedOperationException();
                }
            }
        });
        RespArray respArray = new RespArray(results
                .stream()
                .map(BulkString::new)
                .toArray(Resp[]::new)
        );
        ctx.writeAndFlush(respArray);
    }
}
